/**
 * Foxit Software Inc.
 * Copyright(C) 2005-2014, all rights reserved.
 * The following code is copyrighted and contains proprietary information
 * and trade secrets of Foxit Software Inc.

 * Description: PDFAnnotationLoader
 * Author: shaojie zhuo
 * Update: shaojie zhuo (2014-05-16 16:14)
 */
define(function (require, exports, module) {
    var ImageEngine = WebPDF.ImageEngine;

    /**
     * Annotation加载器
     * @constructor
     * @private
     */
    ImageEngine.PDFAnnotationLoader = function () {
        var _remainedRetryCount = WebPDF.Config.defaults.requestRetryCount;
        var _self = this;

        function _addGroupAnnotToPage(annot, pdfPage) {
            if (pdfPage && annot && annot.getType() === WebPDF.PDFData.AnnotType.MarkUp) {
                var annotGroup = annot.getGroupAnnotMap();
                for (var key in annotGroup) {
                    var groupAnnot = annotGroup[key];
                    pdfPage.addAnnot(groupAnnot);
                    _addGroupAnnotToPage(groupAnnot, pdfPage);
                }
            }
        }

        function _initAnnotation(pdfDocument, jsonAnnotData){
            for (var i = 0; i < jsonAnnotData.length; i++) {
                var jsonPageAnnotData = jsonAnnotData[i];
                var pageNum = jsonPageAnnotData[WebPDF.PDFData.AnnotDataJSONFormat.pageIndex];
                var pdfPage = pdfDocument.getPage(pageNum);
                var jsonAnnots = jsonPageAnnotData[WebPDF.PDFData.AnnotDataJSONFormat.annotations];
                pdfPage.setAnnotJsonData(jsonAnnots);
                for (var j = 0; j < jsonAnnots.length; j++) {
                    var annot = WebPDF.AnnotFactory.createAnnot(jsonAnnots[j]);
                    if(annot){
                        pdfPage.addAnnot(annot);
                        _addGroupAnnotToPage(annot, pdfPage);
                    }
                }
            }
        }

        this.asyncLoadPDFAnnotation = function(readerApp, pdfDocument, doneHandler, failedHandler)
        {
            if(!$.isFunction(doneHandler) || !$.isFunction(failedHandler)){
                $.error("both 'doneHandler' and 'failedHandler' must be function.");
            }
            if (_remainedRetryCount <= 0) {
                console.error('Maximum number of retries exceeded for getAnnotData request.');
                failedHandler(null);
                return;
            }

            var requestData =  { };
            requestData.formMode = readerApp.isFormMode();
            requestData.s3Key = readerApp.getFileID();
            $.ajax({
                url: readerApp.getOptions().url + "annots",
                dataType: 'json',
                data: requestData,
                contentType:"application/x-www-form-urlencoded",
                success: function (response) {
                    var error = response.error;
                    if (error != 0) {
                        if (WebPDF.Common.isNeedRetry(response.status)) {
                            var interval = WebPDF.AjaxRetryManager.getNextAnnotDataRequestInterval(
                                readerApp.getMainView().getDocView().getPageCount());
                            _remainedRetryCount--;
                            setTimeout(function () { _self.asyncLoadPDFAnnotation(readerApp, pdfDocument, doneHandler, failedHandler); }, interval);
                            return;
                        }
                        else {
                            console.error('Get annot data error:' + error);
                            failedHandler(response);
                            return;
                        }
                    }
                    //try {
                        var jsonAnnotData = $.parseJSON(response.data);
                        if (jsonAnnotData != null) {
                            _initAnnotation(pdfDocument,jsonAnnotData);
                        }
                        doneHandler();
                    //}
                   // catch (ex) {
                      //  console.error(ex);
                    //    failedHandler(response);
                    //    return false;
                   // }
                },
                error: function () {
                    failedHandler(null);
                }
            });
        };
    };
});